package com.example.javapracticaltraining.listener;

import com.example.javapracticaltraining.entity.pojo.AiHealthReport;
import com.example.javapracticaltraining.entity.pojo.Elderly;
import com.example.javapracticaltraining.service.AiHealthReportService;
import com.example.javapracticaltraining.service.ElderlyService;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Objects;

@Component
@RabbitListener(queues = "mail")
public class MailQueueListener {
	private static final Logger logger = LoggerFactory.getLogger(MailQueueListener.class);

	@Resource
	JavaMailSender mailSender;

	@Resource
	AiHealthReportService aiHealthReportService;

	@Resource
	ElderlyService elderlyService;

	@Value("${spring.mail.username}")
	String username;

	@RabbitHandler
	public void sendMail(Map<String, Object> data){
		String type = (String) data.get("type");

		SimpleMailMessage message = null;

		switch (type) {
			case "reset" -> {
				String email = data.get("email").toString();
				Integer code = (Integer) data.get("code");
				message = createMessage("密码重置邮件", "你好，您正在进行重置密码操作，验证码：" + code + "，有效时间为3分钟，如非本人操作，请忽略该邮件！", email);
			}
			case "health_report" -> {
				try {
					// 获取报告信息
					Integer reportId = (Integer) data.get("reportId");
					String reportType = (String) data.get("reportType");
					String targetRole = (String) data.get("targetRole");
					Integer elderlyId = (Integer) data.get("elderlyId");

					// 获取报告详情
					AiHealthReport report = aiHealthReportService.getById(reportId);
					if (report == null) {
						logger.error("未找到健康报告: reportId=" + reportId);
						return;
					}

					// 获取老人信息
					Elderly elderly = elderlyService.getById(elderlyId);
					if (elderly == null) {
						logger.error("未找到老人信息: elderlyId=" + elderlyId);
						return;
					}

					// 构建邮件内容
					String title = getReportTitle(elderly.getName(), reportType);
					String content = buildReportEmailContent(report, elderly, reportType, targetRole);

					// 确定收件人邮箱
					// 注意：由于Elderly实体中没有email字段，这里使用紧急联系人电话作为示例
					// 在实际应用中，应该根据实际情况配置收件人邮箱
					String recipientEmail = "awking@al2s.com"; // 默认收件人

					if ("family".equals(targetRole) && elderly.getUrgencyContact() != null) {
						// 在实际应用中，这里应该是家属的邮箱
						recipientEmail = "awking@al2s.com";
					} else if ("doctor".equals(targetRole)) {
						// 在实际应用中，这里应该是医生的邮箱
						recipientEmail = "awking@al2s.com";
					}

					message = createMessage(title, content, recipientEmail);
					logger.info("准备发送健康报告邮件: 老人=" + elderly.getName() + ", 报告类型=" + reportType + ", 目标角色=" + targetRole);
				} catch (Exception e) {
					logger.error("处理健康报告邮件时出错", e);
					return;
				}
			}
			default -> {
				logger.warn("未知的邮件类型: " + type);
				return;
			}
		}

		if (message == null) {
			return;
		}

		try {
			mailSender.send(message);
			logger.info("邮件发送成功: " + message.getTo()[0]);
		} catch (Exception e) {
			logger.error("邮件发送失败", e);
		}
	}

	/**
	 * 获取报告标题
	 * @param elderlyName 老人姓名
	 * @param reportType 报告类型
	 * @return 报告标题
	 */
	private String getReportTitle(String elderlyName, String reportType) {
		return switch (reportType) {
			case "daily" -> elderlyName + "的每日健康报告";
			case "weekly" -> elderlyName + "的每周健康报告";
			case "monthly" -> elderlyName + "的每月健康报告";
			default -> elderlyName + "的健康报告";
		};
	}

	/**
	 * 构建报告邮件内容
	 * @param report 健康报告
	 * @param elderly 老人信息
	 * @param reportType 报告类型
	 * @param targetRole 目标角色
	 * @return 邮件内容
	 */
	private String buildReportEmailContent(AiHealthReport report, Elderly elderly, String reportType, String targetRole) {
		StringBuilder content = new StringBuilder();

		// 添加称呼
		if ("family".equals(targetRole)) {
			content.append("尊敬的").append(elderly.getName()).append("家属：\n\n");
		} else if ("doctor".equals(targetRole)) {
			content.append("尊敬的医生：\n\n");
		} else {
			content.append("尊敬的用户：\n\n");
		}

		// 添加报告类型说明
		switch (reportType) {
			case "daily" -> content.append("这是").append(elderly.getName()).append("的每日健康报告。\n\n");
			case "weekly" -> content.append("这是").append(elderly.getName()).append("的每周健康报告。\n\n");
			case "monthly" -> content.append("这是").append(elderly.getName()).append("的每月健康报告。\n\n");
			default -> content.append("这是").append(elderly.getName()).append("的健康报告。\n\n");
		}

		// 添加报告内容
		content.append("报告摘要：\n").append(report.getSummary()).append("\n\n");

		if (report.getHealthTrends() != null && !report.getHealthTrends().isEmpty()) {
			content.append("健康趋势：\n").append(report.getHealthTrends()).append("\n\n");
		}

		if (report.getCarePoints() != null && !report.getCarePoints().isEmpty()) {
			content.append("护理重点：\n").append(report.getCarePoints()).append("\n\n");
		}

		if (report.getRiskAssessment() != null && !report.getRiskAssessment().isEmpty()) {
			content.append("风险评估：\n").append(report.getRiskAssessment()).append("\n\n");
		}

		if (report.getRecommendations() != null && !report.getRecommendations().isEmpty()) {
			content.append("建议：\n").append(report.getRecommendations()).append("\n\n");
		}

		// 添加结束语
		content.append("如需查看完整报告，请登录系统查看详情。\n\n");
		content.append("此邮件由系统自动发送，请勿回复。");

		return content.toString();
	}

	private SimpleMailMessage createMessage(String title,String  content,String email) {
		SimpleMailMessage message = new SimpleMailMessage();
		message.setSubject(title);
		message.setText(content);
		message.setTo(email);
		message.setFrom(username);
		return message;

	}
}
